package com.youen.service;

import com.youen.dto.vo.AjaxDoneVO;
import com.youen.dto.vo.user.UserVO;
import com.youen.entity.User;
import com.youen.repository.UserRepository;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by Dell on 2018/9/7.
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public String findUserByPage(String name,int pageIndex,int pageSize){
        UserVO userVO = new UserVO();
        Pageable pageable = PageRequest.of(pageIndex > 0 ? pageIndex - 1 : 0, pageSize, new Sort(Sort.Direction.DESC, "id"));
        Page<User> page = userRepository.findByPage(pageable);
        userVO.setTotalRow(page.getTotalElements());
        userVO.setList(page.getContent());
        return JSONObject.fromObject(userVO).toString();
    }

    public String addUser(User user){
        user.setId(UUID.randomUUID().toString());
        userRepository.save(user);
        return JSONObject.fromObject(new AjaxDoneVO("200", "新增成功！")).toString();
    }
}
